<script setup lang="ts">
import { useAttrs, ref } from 'vue';
import $data, { requestSwapData, onFormData } from "xcore/data"
const attrs = useAttrs();
const detail = ref(null)
const rules = ref<any>({})
const formRef = ref(null)

// 初始化数据
requestSwapData((data) => {
  console.log("requestSwapData.detail", data)
  detail.value = data
  detail.value.status = data.status == 1
})
onFormData(async () => {
  try {
    const formData = await validateForm(); // 等待验证结果
    return formData; // 验证通过，返回 detail 数据
  } catch {
    return null; // 返回 null 或其他错误标识
  }
});
const validateForm = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      if (valid) {
        resolve({ table_id: (attrs.DbTable as any)?.id, data: detail.value }); // 验证通过，返回 detail 数据
      } else {
        reject(null); // 验证失败，返回错误字段
      }
    });
  });
};


// 构建验证规则
if ((attrs.DbTable as any)?.id) {
  $data.provider.meta.getMetaTable((attrs.DbTable as any)?.id).then((res: any) => {
    let columns = res.columns
    if (!columns) return;
    columns.forEach((item: any) => {
      if (item.is_nullable === false) {
        let field = (attrs.fields as any[])?.find((field: any) => field.fieldId === item.column_id)
        if (!field) return;
        rules.value[field.name] = [{ required: true, message: `请输入${item.title}`, trigger: 'blur' }]
      }
    })
  })
}

</script>
<template>
  <div>
    {{ detail }}
    <el-form v-bind="$attrs" :model="detail" :rules="rules" ref="formRef">
      <el-row v-if="$attrs.layoutNum >= 1">
        <el-col :span="Math.floor(24 / $attrs.layoutNum)" v-for="field in $attrs['fields']" :key="field.name">
          <el-form-item class="w-100" :prop="field.name" :label="$attrs.showLabel ? field.title : ''">
            <x-cmpnt-renders fullRow="true" :cmpnts="$data.func.createCmpnt(field)" :data="detail"></x-cmpnt-renders>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="w-100" v-else v-for="field in $attrs['fields']" :key="field"
        :label="$attrs.showLabel ? field.title : ''" :prop="field.name">
        <x-cmpnt-renders fullRow :cmpnts="$data.func.createCmpnt(field)" :data="detail" :parent="{}"></x-cmpnt-renders>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped></style>